/* Copyright 2012 Dustin Mitchell <dmmitche [at] gmail [dot] com>
 *
 * Licensed under the GPLv3.  See included LICENSE.txt for full details.
 */

#include <stdlib.h>

#include "service.h"

struct trampoline_arg
{
  struct message_queue *queue;
  void (*ep) (struct message_queue *, void *);
  void *user_obj;
};

static void * service_trampoline (void *arg)
{
  struct trampoline_arg *targ = (struct trampoline_arg *)arg;

  targ->ep (targ->queue, targ->user_obj);

  free (targ);

  return NULL;
}



int service_start (struct service *svc, struct message_queue *queue,
                   void (*ep)(struct message_queue *, void *), void *user_obj)
{
  struct trampoline_arg *arg;

  if (!svc)
    return -1;

  arg = (struct trampoline_arg *)malloc (sizeof (struct trampoline_arg));

  if (!arg)
    return -1;

  arg->queue = queue;
  arg->ep = ep;
  arg->user_obj = user_obj;

  if (pthread_create (&svc->thread_id, NULL, service_trampoline, arg) != 0) {
    free (arg);
    return -1;
  }

  return 0;
}

int service_wait (struct service *svc)
{
  if (!svc)
    return -1;

  if (pthread_join (svc->thread_id, NULL) != 0)
    return -1;

  return 0;
}
